package com.pro.common.service.file.service;

import com.pro.common.api.model.BaseModel;
import com.pro.common.api.statics.user.file.storage.service.IFileStorageService;
import com.pro.common.api.user.file.enums.EnumFileNodeType;
import com.pro.common.api.user.file.model.db.UserFile;
import com.pro.common.api.user.file.model.db.UserFileNode;
import com.pro.common.service.file.dao.UserFileDao;
import com.pro.framework.mybatisplus.BaseService;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 支付渠道 服务实现类
 */
@Service
public class UserFileService extends BaseService<UserFileDao, UserFile> {
    public UserFile getOne(Long fileNodeId) {
        UserFile param = new UserFile();
        param.setFileNodeId(fileNodeId);
        return this.getOne(param);
    }

    public Map<Long, UserFile> getMap(List<Long> userFileNodeIds) {
        if (userFileNodeIds.isEmpty()) {
            return Collections.emptyMap();
        }
        return this.getMap(UserFile::getFileNodeId, userFileNodeIds, UserFile::getFileNodeId);
    }

    public void fillUrl(IFileStorageService fileStorageService, List<UserFileNode> records) {
        if (records.isEmpty()) {
            return;
        }
        List<UserFileNode> fileNodesFile = records.stream().filter(f -> EnumFileNodeType.FILE.equals(f.getType())).toList();
        List<Long> userFileNodeIds = fileNodesFile.stream().map(BaseModel::getId).toList();
        Map<Long, UserFile> fileNodeIdMap = getMap(userFileNodeIds);
        Map<Long, String> userFileMap = this.getUrlMap(fileStorageService, fileNodeIdMap.values());
        fileNodesFile.forEach(fileNodeFile -> {
            fileNodeFile.setStatus(fileNodeIdMap.get(fileNodeFile.getId()).getStatus());
            fileNodeFile.setUrl(userFileMap.get(fileNodeFile.getId()));
        });
    }

    private Map<Long, String> getUrlMap(IFileStorageService fileStorageService, Collection<UserFile> userFiles) {
        return userFiles.stream().collect(Collectors.toMap(
                UserFile::getFileNodeId,
                userFile -> fileStorageService.getObjectUrlPublic(userFile.getBucket(), userFile.getStorageKey())
        ));

    }
}
